<template>
  <basic-container>
    <avue-crud :option="roleOption"
               :table-loading="loading"
               :data="data"
               ref="crud"
               :row-style="rowStyle"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button size="small" icon="el-icon-plus" @click="handleAdd" v-if="permission.role_add">新增</el-button>
        <el-button size="small" icon="el-icon-delete" v-if="permission.role_delete" @click="handleDelete">删 除</el-button>
        <el-button size="small" icon="el-icon-setting" @click="handleRole" v-if="userInfo.role_name.includes('admin')">权限设置
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-row type="flex" class="row-bg" justify="center">
          <el-col :span="6">
            <el-tooltip class="item" effect="dark" content="详情" placement="bottom">
              <div class="iconclick" @click="openView(scope.row,scope.index)"><span class="iconnew icon-chakan"></span></div>
            </el-tooltip>
          </el-col>
          <el-col :span="6">
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
              <div class="iconclick" @click="openEdit(scope.row,scope.index)"><span class="iconnew icon-bianji"></span></div>
            </el-tooltip>
          </el-col>
          <el-col :span="6">
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <div class="iconclick"  @click="rowDel(scope.row)"><span class="iconnew icon-tubiaozhizuo-"></span></div>
            </el-tooltip>
          </el-col>
        </el-row>
      </template>
    </avue-crud>
    <el-dialog title="角色权限配置"
               append-to-body
               :visible.sync="box"
               width="500px"  center>
      <el-tabs type="border-card">
        <el-tab-pane label="菜单权限">
          <el-tree :data="menuGrantList"
                   show-checkbox
                   node-key="id"
                   ref="treeMenu"
                   :default-checked-keys="menuTreeObj"
                   :props="props">
          </el-tree>
        </el-tab-pane>
<!--        <el-tab-pane label="数据权限">-->
<!--          <el-tree :data="dataScopeGrantList"-->
<!--                   show-checkbox-->
<!--                   node-key="id"-->
<!--                   ref="treeDataScope"-->
<!--                   :default-checked-keys="dataScopeTreeObj"-->
<!--                   :props="props">-->
<!--          </el-tree>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="接口权限">-->
<!--          <el-tree :data="apiScopeGrantList"-->
<!--                   show-checkbox-->
<!--                   node-key="id"-->
<!--                   ref="treeApiScope"-->
<!--                   :default-checked-keys="apiScopeTreeObj"-->
<!--                   :props="props">-->
<!--          </el-tree>-->
<!--        </el-tab-pane>-->
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="box = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submit" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {add, getList, getRole, getRoleTree, grant, grantTree, remove, update,} from "@/api/system/role";
  import {roleOption} from '@/const/authority/role'
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        box: false,
        props: {
          label: "title",
          value: "key"
        },
        menuGrantList: [],
        dataScopeGrantList: [],
        apiScopeGrantList: [],
        apiGrantList: [],
        menuTreeObj: [],
        dataScopeTreeObj: [],
        apiScopeTreeObj: [],
        selectionList: [],
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        roleOption,
        data: [],
        selIndex:[]
      };
    },
    computed: {
      ...mapGetters(["userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.role_add, false),
          viewBtn: this.vaildData(this.permission.role_view, false),
          delBtn: this.vaildData(this.permission.role_delete, false),
          editBtn: this.vaildData(this.permission.role_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);

        });
        return ids.join(",");
      },
      idsArray() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids;
      }
    },
    methods: {
      rowStyle({row,column,rowIndex}){
        let arr = this.selIndex || []
        if (this.selIndex.includes(row.id)) {
          return {
            // 'background-color':"#FBEBEB"
            'background-color':"#ecf5ff"
          }
        }
      },
      openView(row,index){
        this.$refs.crud.rowView(row,index)
      },
      handleAdd(){
        this.$refs.crud.rowAdd();
      },
      initData(){
        getRoleTree().then(res => {
          const column = this.findObject(this.option.column, "parentId");
          column.dicData = res.data.data;
        });
      },
      submit() {
        const menuList = this.$refs.treeMenu.getCheckedKeys();
        // const dataScopeList = this.$refs.treeDataScope.getCheckedKeys();
        // const apiScopeList = this.$refs.treeApiScope.getCheckedKeys();
        const dataScopeList = [];
        const apiScopeList = [];
        grant(this.idsArray, menuList, dataScopeList, apiScopeList).then(() => {
          this.box = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.onLoad(this.page);
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      openEdit(row,index){
        this.$refs.crud.rowEdit(row,index)
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row){
        this.$confirm("确定将选择数据删除?", "提示",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done){
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list
        let ids = list.map((item) => {
          return item.id
        })
        let arr =  []
        this.data.map((item, index) => {
          for (let i in ids) {
          if (item.id === ids[i]) {
            arr.push(item.id)
          }
        }
      })
        this.selIndex = arr
        console.log(this.selIndex)
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      beforeOpen(done, type) {
        if (["add", "edit"].includes(type)) {
          this.initData();
        }
        done();
      },
      handleRole() {
        if (this.selectionList.length !== 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        this.menuTreeObj = [];
        this.dataScopeTreeObj = [];
        this.apiScopeTreeObj = [];
        grantTree()
          .then(res => {
            this.menuGrantList = res.data.data.menu;
            this.dataScopeGrantList = res.data.data.dataScope;
            this.apiScopeGrantList = res.data.data.apiScope;
            getRole(this.ids).then(res => {
              this.menuTreeObj = res.data.data.menu;
              this.dataScopeTreeObj = res.data.data.dataScope;
              this.apiScopeTreeObj = res.data.data.apiScope;
              this.box = true;
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", '提示',{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          this.data = res.data.data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
  .rowStyle{
    /*background-color:#FBEBEB !important;*/
    background-color:#ecf5ff !important;
  }
</style>
